<!--
@ 作者: 阿拉丁矿工 黄传鸿 <hchhyzc@foxmail.com>
-->
<template>
  <div class="center">
    <!-- 菜单工具条  设备数据-->
    <div class="h_heard">
      <div class="h_heard_left_icon"></div>
      <div class="h_heard_midol">设备数据</div>
      <div class="h_heard_right">
        <div class="h_flex_row_center">
          <!-- 新建 -->
          <div style="width: 10px"></div>
          <NTooltip placement="bottom" trigger="hover">
            <template #trigger>
              <svg class="h_tool_icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" :width="IconSize"
                :height="IconSize" viewBox="0 0 1024 1024" v-html="onGetDataManagerIcon('dataAddIcon')"
                @click="onequipsAdd"></svg>
            </template>
            <span>新建</span>
          </NTooltip>
          <!-- 删除 -->
          <div style="width: 10px"></div>
          <NTooltip placement="bottom" trigger="hover">
            <template #trigger>
              <svg class="h_tool_icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" :width="IconSize"
                :height="IconSize" viewBox="0 0 1024 1024" v-html="onGetDataManagerIcon('dataDeleteIcon')"
                @click="onequipsDelete"></svg>
            </template>
            <span>删除</span>
          </NTooltip>
          <!-- 全部删除 -->
          <div style="width: 10px"></div>
          <NTooltip placement="bottom" trigger="hover">
            <template #trigger>
              <svg class="h_tool_icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" :width="IconSize"
                :height="IconSize" viewBox="0 0 1024 1024" v-html="onGetDataManagerIcon('dataSetAllDeleteIcon')"
                @click="onequipsDeleteAll"></svg>
            </template>
            <span>全部删除</span>
          </NTooltip>
          <!-- 下载 -->
          <div style="width: 10px"></div>
          <NTooltip placement="bottom" trigger="hover">
            <template #trigger>
              <svg class="h_tool_icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" :width="IconSize"
                :height="IconSize" viewBox="0 0 1024 1024" v-html="onGetDataManagerIcon('dataSetGetIcon')"
                @click="onequipsDownload()"></svg>
            </template>
            <span>下载</span>
          </NTooltip>

          <!-- 保存 -->
          <div style="width: 10px"></div>
          <NTooltip placement="bottom" trigger="hover">
            <template #trigger>
              <svg class="h_tool_icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" :width="IconSize"
                :height="IconSize" viewBox="0 0 1024 1024" v-html="onGetDataManagerIcon('dataSetSaveIcon')"
                @click="onProjectSave()"></svg>
            </template>
            <span>保存</span>
          </NTooltip>

          <!-- 导入 -->
          <div style="width: 10px"></div>
          <NTooltip placement="bottom" trigger="hover">
            <template #trigger>
              <svg class="h_tool_icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" :width="IconSize"
                :height="IconSize" viewBox="0 0 1024 1024" v-html="onGetDataManagerIcon('dataInExcelIcon')"
                @click="onOpenFileDialog()"></svg>
            </template>
            <span>导入Excel表格</span>
          </NTooltip>

          <!-- 导出 -->
          <div style="width: 10px"></div>
          <NTooltip placement="bottom" trigger="hover">
            <template #trigger>
              <svg class="h_tool_icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" :width="IconSize"
                :height="IconSize" viewBox="0 0 1024 1024" v-html="onGetDataManagerIcon('dataOutExcelIcon')"
                @click="onequipsLeadingOut()"></svg>
            </template>
            <span>导出Excel表格</span>
          </NTooltip>
          <div style="width: 10px"></div>
        </div>
      </div>
    </div>
    <!-- 中间窗体 -->
    <div class="center_content">
      <!-- 数据表格 -->
      <n-data-table :columns="Columns" :data="equipData" :max-height="500" :pagination="Pagination"
        :row-props="onSelectRow" />
    </div>
    <!-- 文件导入 -->
    <input type="file" style="display: none" ref="fileRef" @change="onequipsLeadingIn" />
  </div>
</template>

<script setup lang="ts">
/* ================================================================================================ */
// 🍀引入 ★
/* ================================================================================================ */
import { h, ref, reactive, computed, watch, onMounted } from "vue";
import axios from "axios";
import * as XLSX from "xlsx";
import { useMessage } from 'naive-ui';
import { NInput, NInputNumber, NSelect, NColorPicker } from "naive-ui";
import type { DataTableColumns } from "naive-ui";

/**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
// 🐸 图元端函数引入
/**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
import {
  onGetDataManagerIcon,
  onProjectSave,
  onActionRightNavigation,// 激活右框导航
  onCreateChannelOpt, // 创建 设备数据 选项
  onCreateReadEquipsOpt,  // 创建_设备数据_读_选项
  onCreateWriteEquipsOpt, // 创建_设备数据_写_选项
  onReadExcelFile, // 根据sheet索引读取Excel文件中的数据
  onRecordLog, // 日志处理器
  onGetUUID, // 获取UUID
} from "@/functions";

/**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
// 🐸 引入存储
/**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
import { useMenuStore } from "@/store/menuStore"; // 菜单
import { useCanvasStore } from "@/store/canvasStore"; // 画布
import { useProjectStore } from "@/store/projectStore"; // 工程
import { useLayoutStore } from "@/store/layoutStore"; // 布局
import { useStaticStore } from "@/store/staticStore"; // 静态
import { useWorkStore } from "@/store/workStore"; // 工作数据

/**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
// 🐸 使用存储
/**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
const menuStore = useMenuStore(); // 菜单
const canvasStore = useCanvasStore(); // 画布
const projectStore = useProjectStore(); // 工程
const staticStore = useStaticStore(); // 静态
const workStore = useWorkStore(); // 设备数据
const message = useMessage()// 消息
/* ================================================================================================ */
//                                数据 ★
/* ================================================================================================ */
/** 文件参数 */
let fileRef = ref();
/** 设备 */
const channels = computed(() => workStore.channels);
/** 设备数据 */
const equipData = computed(() => workStore.equipData);

/**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
// 🐸 引入 选项
/**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
/** 设备数据类型:0_布尔;1_8位;2_16位;3_16位;4_32位;5_字符; */
const equipDataTypeOpt = staticStore.equipDataTypeOpt;
/** 设备_读写模式选项 */
const readWriteOpt = staticStore.readWriteOpt;
/** 图元数据_集选项 */
const pelDataOpt = computed(() => canvasStore.equipData);
/** 设备数据_选项 */
const channelsOpt = computed(() => canvasStore.channelsOpt);
/** 请求类型选项:1-GET;2-POST;3-PUSH */
const requestTypeOpt = staticStore.requestTypeOpt;
/** 请求数周期选项:1-0.1秒; 2-0.5秒;3-1秒;4-1分钟;5-1小时; 6-1天; */
const requestCycelOpt = staticStore.requestCycelOpt;
/** 行数据定义 */
type RowData = {
  equipDataDescr: string;  // 说明
  equipDataLabel: string; // 标签名
  equipDataId: string;   // 设备id
  equipDataType: string; // 设备数据类型:0_布尔;1_8位;2_16位;3_16位;4_32位;5_字符;
  equipDataRW: number;   // 读写选项:0_读;1_写;
  equipDataVal: string;  // 设备变量值
};
/** 列标 */
let Columns: DataTableColumns<RowData> = [
  // 名称 equipDataDescr
  {
    title: "说明",
    key: "equipDataDescr",
    sorter: "default",
    resizable: true,
    minWidth: 100,
    maxWidth: 500,
    render(row, index) {
      return h(NInput, {
        value: row.equipDataDescr,
        onUpdateValue(v) {
          workStore.equipData[index].equipDataDescr = v;
        },
      });
    },
  },
  // 标签名 equipDataLabel
  {
    title: "标签名",
    key: "equipDataLabel",
    sorter: "default",
    resizable: true,
    minWidth: 100,
    maxWidth: 500,
    render(row, index) {
      return h(NInput, {
        value: row.equipDataLabel,
        onUpdateValue(v) {
          workStore.equipData[index].equipDataLabel = v;
        },
      });
    },
  },
  // 读写 equipDataRW
  {
    title: "读写设备",
    key: "equipDataRW",
    sorter: "default",
    resizable: true,
    width: 80,
    minWidth: 80,
    maxWidth: 100,
    render(row, index) {
      return h(NSelect, {
        value: row.equipDataRW,
        options: readWriteOpt,
        onUpdateValue(v) {
          workStore.equipData[index].equipDataRW = v;
        },
      });
    },
  },
  // 设备 channelId
  {
    title: "通道",
    key: "channelId",
    sorter: "default",
    resizable: true,
    minWidth: 100,
    maxWidth: 500,
    render(row, index) {
      return h(NSelect, {
        value: row.channelId,
        options: channelsOpt.value,
        onUpdateValue(v) {
          workStore.equipData[index].channelId = v;
        },
      });
    },
  },
  // 数据类型 equipDataType
  {
    title: "设备数据类型",
    key: "equipDataType",
    sorter: "default",
    resizable: true,
    width: 120,
    minWidth: 120,
    maxWidth: 200,
    render(row, index) {
      return h(NSelect, {
        value: row.equipDataType,
        options: equipDataTypeOpt,
        onUpdateValue(v) {
          workStore.equipData[index].equipDataType = v;
        },
      });
    },
  },
  // 变量值 Val
  {
    title: "变量值",
    key: "equipDataVal",
    sorter: "default",
    resizable: true,
    minWidth: 100,
    maxWidth: 500,
    render(row, index) {
      return h(NInput, {
        value: row.equipDataVal,
        onUpdateValue(v) {
          workStore.equipData[index].equipDataVal = v;
        },
      });
    },
  },
  // 设备数据id equipDataId
  {
    title: "设备id",
    key: "equipDataId",
    minWidth: 100,
    maxWidth: 500,
  }
];
/** 分页 */
let Pagination = { pageSize: 1000 };
/** 图标尺寸 */
const IconSize = 30;

/* ================================================================================================ */
//                                函数 ★
/* ================================================================================================ */
/** 选择行 */
const onSelectRow = (Row: RowData) => {
  return {
    onClick: () => {
      // console.log(Row)
      /** ★ 赋值-选择的行数据 */
      canvasStore.selectedEquip = Row;
      onActionRightNavigation('RightChannel')  // 激活右框导航
    },
  };
};

/** 设备数据-添加 */
const onequipsAdd = () => {
 // console.log("§ 设备数据-添加")
  /** ★ 添加数据 */
  let AddData = {
    equipDataId: "E" + onGetUUID(), // 设备id;
    equipDataDescr: onGetUUID(),     // 设备名称;
    equipDataLabel: onGetUUID(),    // 标签;
    equipDataType: 0,               // 设备数据类型:0_布尔;1_8位;2_16位;3_16位;4_32位;5_字符;
    equipDataRW: 0,                 // 读写选项:0_读;1_写;
    channelId: "",                // 通道Id;
    equipDataVal: "1",              // 变量值;
  };

  /** ★ 添加 */
  workStore.equipData.push(AddData);

  /** ★ 清空-选择的行数据 */
  canvasStore.selectedEquip = [];
};

/** 设备数据-删除 */
const onequipsDelete = () => {
 // console.log("§ 设备数据-删除")


  /** ★ 查找id */
  let equipDataId = String(canvasStore.selectedEquip.equipDataId);
 // console.log(id)

  /** ★ 根据id删除元素 */
  let Attribute = JSON.parse(JSON.stringify(workStore.equipData));
 // console.log(Attribute)
  for (let index = 0; index < Attribute.length; index++) {
    const element = Attribute[index];
    if (String(element.equipDataId) === equipDataId) {
      Attribute.splice(index, 1);
    }
  }

 // console.log(Attribute)
  /** ★ 清空数据 */
  canvasStore.selectedEquip = [];
  workStore.equipData = [];

  /** ★ 赋值-设备数据 */
  workStore.equipData = Attribute;
};

/** 设备数据-删除全部 */
const onequipsDeleteAll = () => {
 // console.log("§ 设备数据-删除全部")
  workStore.equipData = [];
};

/** 设备数据-下载 */
const onequipsDownload = () => {
 // console.log("§ 设备数据-下载")
  /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  // 🐸 发送-工程数据
  /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  axios({
    url: `/api/HCIOT?query=getEquipSet`,
    method: "get",
  })
    .then((response: any) => {
      if (response.status === 200) {
        /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
        // 🐸 转储- 设备数据存储
        /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
       // console.log(response.data)
        workStore.equipData = response.data.equip;
        workStore.channels = response.data.channels;

        /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
        // 🐸 提示 记录到日志
        /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

        onRecordLog("获取 设备数据 成功");
        message.success("获取成功");
      } else {
        onRecordLog("获取 设备数据 失败");
        message.error("获取 设备数据 失败");
      }
    })
    .catch((error: any) => {
      onRecordLog("获取 设备数据 失败");
      message.error("获取 设备数据 失败");
    });
};

/** 设备数据-导出 */
const onequipsLeadingOut = () => {
 // console.log("§ 设备数据-导出")
  const ws = XLSX.utils.json_to_sheet(workStore.equipData);
  const wb = XLSX.utils.book_new();
  const fileName = "设备数据.xlsx";
  XLSX.utils.book_append_sheet(wb, ws, "设备数据");
  XLSX.writeFile(wb, fileName);
};

/** 打开文件对话框 */
const onOpenFileDialog = () => {
 // console.log("打开文件对话框")
 // console.log(fileRef.value)
  fileRef.value.dispatchEvent(new MouseEvent("click"));
};

/**  设备数据-导入 */
const onequipsLeadingIn = () => {
 // console.log("设备数据-导入")
 // console.log(fileRef)
 // console.log(fileRef.value.files[0])
  let f = fileRef.value.files[0];
  workStore.equipData = onReadExcelFile(f, 0);
};

/* ================================================================================================ */
//                                ★ 钩子函数_挂载后
/* ================================================================================================ */
onMounted(() => {
 // console.log("钩子函数_挂载后")
  onCreateChannelOpt(); // 创建_通道数据_选项
  onCreateReadEquipsOpt();  // 创建_设备数据_读_选项
  onCreateWriteEquipsOpt(); // 创建_设备数据_写_选项
});


</script>

<style lang="scss" scoped>
/* 引入共用css */
@import "@/assets/h.scss";
.center {
  width: 100%;
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.center_content {
  flex: 1;
}

//图标
.h_tool_icon {
  user-select: none;
  cursor: pointer;
  border-radius: 5px;
  background-color: rgb(0, 100, 00);

  &:hover {
    background-color: rgb(255, 255, 255);
  }
}

.file_input {
  display: none;
}
</style>
